﻿@implements IAsyncDisposable

<div @ref=ContainerElementRef></div>

@code {
    private ElementReference ContainerElementRef { get; set; }

    private DotNetObjectReference<ReactSampleRenderer> DotNetObjectRef { get; set; }

    private IJSObjectReference JsModule { get; set; }

    [Inject]
    public IJSRuntime JSRuntime { get; set; }

    [Parameter]
    public ReactSampleModel Model { get; set; }

    protected async override Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (JsModule == null)
        {
            var jsModuleFile = "./Editors/ReactSampleRenderer.razor.js";
            JsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", jsModuleFile);
            DotNetObjectRef = DotNetObjectReference.Create(this);
            await JsModule.InvokeVoidAsync("init", ContainerElementRef, DotNetObjectRef);
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (JsModule != null)
        {
            await JsModule.DisposeAsync();
            JsModule = null;
        }

        if (DotNetObjectRef != null)
        {
            DotNetObjectRef.Dispose();
            DotNetObjectRef = null;
        }

        GC.SuppressFinalize(this);
    }

    public static RenderFragment Create(ReactSampleModel model)
    {
        return @<ReactSampleRenderer Model="@model" />;
    }
}
